package com.example.emos.wx.config.shiro;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
@Scope("prototype") // 多例
public class OAuth2Filter extends AuthenticatingFilter {

    @Autowired
    private ThreadLocalToken threadLocalToken;

    @Value("${emos.jwt.cache-expire}")
    private int cacheExpire;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 拦截请求之后，用于把令牌字符串封装成令牌对象
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        // 获取token
        String token = getRequestToken((HttpServletRequest) servletRequest);
        if(StrUtil.isBlank(token)) {
            return null;
        }
        return new OAuth2Token(token);
    }

    /**
     * 拦截请求，判断请求是否需要被Shiro处理
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest req = (HttpServletRequest) request;
        // Ajax提交application/json数据的时候，会先发出Options请求
        // 这里要放行Options请求，不需要Shiro处理
        if(req.getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }
        // 除了Options请求之外，所有请求都要被Shrio处理
        return false;
    }

    /**
     * 当isAccessAllowed()返回false的时候，代表应该被shrio处理，onAccessDenied()方法执行
     * 该方法用于处理所有应该被Shrio处理的请求
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        // 允许跨域请求
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Orign", req.getHeader("Origin"));
        threadLocalToken.clear();

        // 获取token，如果token不存在，直接返回401
        String token = getRequestToken(req);
        if(StrUtil.isBlank(token)) {
            resp.setStatus(HttpStatus.SC_UNAUTHORIZED); // 401
            resp.getWriter().print("无效的令牌");
            return false; // 返回错误，后端不需要再进行后期的shrio认证等等操作(因为令牌有问题)
        }
        try {
            jwtUtil.verifierToken(token); // 检查令牌是否过期(try.catch判断是内容有问题，还是过期了)
        } catch (TokenExpiredException e) { // TokenExpiredException:代表过期异常
            // 客户端令牌过期，查询Redis中是否存在令牌，如果存在令牌就重新生成一个令牌给客户端
            if(redisTemplate.hasKey(token)) {
                redisTemplate.delete(token); // 在redis中删除令牌
                int userId = jwtUtil.getUserId(token);
                token = jwtUtil.createToken(userId); // 生成新的令牌
                // 把新的令牌保存到redis中
                redisTemplate.opsForValue().set(token, userId + "", cacheExpire, TimeUnit.DAYS);
                //把新的令牌绑定到线程
                threadLocalToken.setToken(token);
            } else { // 如果redis中不存在令牌，让用户重新登陆
                resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
                resp.getWriter().print("令牌已经过期");
                return false;
            }
        } catch (Exception e) { // Exception：内容的异常
            resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
            resp.getWriter().print("无效的令牌");
            return false;
        }
        boolean b = executeLogin(servletRequest, servletResponse); // 间接的让shrio执行OAuth2Realm
        return b; // b代表认证、授权是否成功
    }

    /**
     * 用户登录失败或没有登陆（只是认证失败会执行，授权失败并不执行）
     * 而onAccessDenied中的b无法判断是认证失败还是授权失败
     * @param token
     * @param e
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setStatus(HttpStatus.SC_UNAUTHORIZED); // 401
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
        try {
            resp.getWriter().print(e.getMessage());
        } catch (IOException exception) {
            // 打印到控制台或者写入日志，这里就不处理了
        }
        return false; // 认证失败，肯定返回false
    }

    /**
     * 获取请求头里的token
     * @param httpServletRequest
     * @return
     */
    private String getRequestToken(HttpServletRequest httpServletRequest) {
        // 从header中获取token
        String token = httpServletRequest.getHeader("token");
        // 如果header中不存在token，则从参数中获取token
        if(StrUtil.isBlank(token)) {
            token = httpServletRequest.getParameter("token");
        }
        return token;
    }

    @Override
    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse resp= (HttpServletResponse) response;
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
//        super.doFilterInternal(request, response, chain);
        super.doFilterInternal(req, resp, chain);
    }
}
